import React from 'react';
import axios from 'axios';
import './SyContent.css'
import { Input,Table,InputNumber,Button,Modal,message,Popconfirm ,Row,Col} from 'antd';
import {TransactionOutlined} from '@ant-design/icons';
const { Search } = Input;

class SyContent extends React.Component {
    constructor(props){
        super(props);
        this.state={
            totalData:[],//页面预存数据
            visible:false,
            loading:false,
            totalMoney:0,//表格数据的总金额
            data :[],//表格数据
            ssMoney:'',//实收
        };
    }
    showModal = () => {
        if(this.state.data.length>0){
            this.setState({
                visible: true,
            });
        }else {
            message.error('还没有商品，无法结账')
        }
    };
    handleOk = () => {
        if(this.state.ssMoney-this.state.totalMoney>=0){
            this.setState({ loading: true });
            setTimeout(() => {
                message.success(`收款成功，共计${this.state.totalMoney}元，请留意找零${this.state.ssMoney-this.state.totalMoney}元！`);
                this.setState({
                    loading: false,
                    visible: false,
                    data:[],
                    totalMoney:0,
                    ssMoney:'',
                });
            }, 3000);
        }
        else{
            message.error(`结算失败，请注意实收金额！`);
            return false
        }
    };
    handleCancel = () => {
        this.setState({ visible: false },()=>{
            message.error('已取消');
            this.setState({
                ssMoney:'',
            })
        });
    };
    render() {
        const columns = [
            {
                title: '商品编号',
                // minWidth:20,
                width:'20%',
                align:'center',
                dataIndex: 'id',
                key: 'id',
            },
            {
                title: '商品名称',
                // minWidth:20,
                width:'16%',
                align:'center',
                dataIndex: 'name',
                key: 'id',
            },
            {
                title: '单价/元',
                // minWidth:20,
                width:'16%',
                align:'center',
                dataIndex: 'price',
                key: 'id',
            },
            {
                title: '金额/元',
                // minWidth:20,
                width:'16%',
                align:'center',
                dataIndex: 'sum',
                key: 'id',
            },
            {
                title: '数量',
                fixed: 'right',
                align:'center',
                // minWidth:20,
                width:'16%',
                key:'id',
                render: (text, record, index) => {
                    return <InputNumber
                        defaultValue={record.num}
                        value={record.num}
                        min={1}
                        formatter={value =>value.toString().replace(/^(0+)|[^\d]+/g,'') }
                        parser={value =>value.toString().replace(/^(0+)|[^\d]+/g,'')}
                        onChange={(value)=>{
                            //更新state的data
                            if(value) record.num=value;
                            else record.num=1;
                            record.sum=parseInt(record.num)*record.price;
                            let arr=this.state.data;
                            arr[index]=record;
                            //更新state的totalMoney
                            let sum=0;
                            arr.map(item=>sum+=item.sum);
                            //组件更新
                            this.setState({
                                data:arr,
                                totalMoney:sum
                            },()=>{
                                //console.log(this.state);
                            })
                        }}/>
                }
            },
            {
                title: 'Action',
                fixed: 'right',
                align:'center',
                // minWidth:20,
                width:'16%',
                key:'id',
                render: (text, record, index) => {
                    return <Popconfirm
                        title={`是否要删除商品：${text.name}?`}
                        onConfirm={()=>{
                            let arr=[...this.state.data];
                            arr.splice(index,1);
                            let sum=0;
                            arr.map(item=>sum+=item.sum);
                            this.setState({
                                data:arr,
                                totalMoney:sum
                            },()=>{
                                message.success('删除成功')
                            })
                        }}
                        onCancel={ ()=>{message.error('已取消')}}
                        okText="是"
                        cancelText="否">
                        <Button type="primary" danger >删除</Button>
                    </Popconfirm>
                }
            },
        ];
        return (
            <div id="shouyin_content">
                {/*头部信息*/}
                <div id="sy_header">
                    <div>
                        <Search
                            autoFocus
                            placeholder="请扫码或输入商品编号"
                            enterButton="添加"
                            size="large"
                            allowClear
                            onSearch={value=>{
                                if(value===''){
                                    message.warning('输入框不能为空（控制台有数据哦，请输入商品id）');
                                    return false
                                }
                                if(!(/^[0-9]*$/).test(value)){
                                    message.warning('请输入数字编号');
                                    return false
                                }
                                let obj=this.state.totalData.filter(item=> item.id===parseInt(value));
                                if(obj.length>0){
                                    let dataArr=[...this.state.data];
                                    let checkArr=dataArr.filter(item=>item.id===obj[0].id);
                                    if(checkArr.length>0){//列表已存在
                                        dataArr.map(item=>{
                                            if(item.id===obj[0].id){
                                                item.num++;
                                                item.sum=item.num*item.price;
                                            }
                                            return item
                                        })
                                    }else {//列表没有
                                        dataArr.push(obj[0]);
                                    }
                                    let sum=0;
                                    dataArr.map(item=>sum+=item.sum);
                                    this.setState({
                                        data:dataArr,
                                        totalMoney:sum
                                    },()=>{
                                        message.success('添加成功');
                                    });
                                }else {
                                    message.error('该商品不存在');
                                }
                                return false
                            }}
                        />
                    </div>
                    <div>
                        <div>收银员: <span>张三</span></div>
                        <div>日期: <span>2020/4/26</span></div>
                    </div>
                </div>
                {/*主体内容*/}
                <div id="sy_section">
                    <h2>商品订单详情</h2>
                    <div>
                        <Table columns={columns}
                               dataSource={this.state.data}
                               rowKey='id'
                               scroll={{ y: 300}}
                               pagination={false} />
                    </div>
                </div>
                {/*底部信息*/}
                <div id="sy_footer">
                    <div>
                        <Button
                            style={{backgroundColor:"green"}}
                            type="primary" shape="round" size="large"
                            icon={<TransactionOutlined />}
                            onClick={this.showModal}>
                            交易收银
                        </Button>
                    </div>
                    <div>总计：<span style={{color:"red"}}>￥{this.state.totalMoney}</span></div>
                </div>
                {/*弹框*/}
                <Modal
                    visible={this.state.visible}
                    title="收款清单"
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    footer={[
                        <Input
                            id='p_sy_input'
                            style={{marginBottom:'10px'}}
                            value={this.state.ssMoney}
                            key='ssMoney'
                            placeholder='实收金额:元'
                            autoFocus
                            /*formatter={value =>value.toString().replace(/^(0+)|[^\d]+/g,'') }*/
                           /* parser={value =>value.toString().replace(/^(0+)|[^\d]+/g,'')}*/
                            onChange={(e)=>{
                                let value=e.target.value;
                                if (Number(value)){
                                    this.setState({
                                        ssMoney:value
                                    })
                                }else if(value===''){
                                    message.warning('实收金额不能为空');
                                    this.setState({
                                        ssMoney:0
                                    });
                                    return false
                                }else{
                                    message.error('请输入数字');
                                    this.setState({
                                        ssMoney:0
                                    });
                                    return false
                                }
                            }}
                            onBlur={(e)=>{
                                let value=e.target.value;
                                if (Number(value)){
                                    this.setState({
                                        ssMoney:value
                                    })
                                }else if(value===''){
                                    message.warning('实收金额不能为空');
                                    this.setState({
                                        ssMoney:''
                                    });
                                    return false
                                }else{
                                    message.error('请输入数字');
                                    this.setState({
                                        ssMoney:''
                                    });
                                    return false
                                }
                            }}
                            />,
                        <div key='reMoney' style={{textAlign:'left',marginBottom:'10px'}}>找零：<span style={{color:"red",fontSize:'1.5em'}}>￥{this.state.ssMoney-this.state.totalMoney}</span></div>,
                        <Button key="back" onClick={this.handleCancel}>
                            返回
                        </Button>,
                        <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>
                            确认
                        </Button>,
                    ]}
                >
                    <Row justify="center" style={{textAlign:'center'}}>
                        <Col span={6}>名称</Col>
                        <Col span={6}>单价</Col>
                        <Col span={6}>数量</Col>
                        <Col span={6}>小计</Col>
                    </Row>
                    {this.state.data.map((item,index)=> <Row key={index} justify="center" style={{textAlign:'center'}}>
                        <Col span={6}>{item.name}</Col>
                        <Col span={6}>{item.price}元</Col>
                        <Col span={6}>{item.num}</Col>
                        <Col span={6}>{item.sum}元</Col>
                    </Row>)}
                    <Row justify="center" style={{textAlign:'center',marginTop:'20px'}}>
                        <Col span={6}/>
                        <Col span={6}/>
                        <Col span={6}/>
                        <Col span={6}>合计：<span style={{color:"red"}}>￥{this.state.totalMoney}</span></Col>
                    </Row>
                </Modal>
            </div>
        )
    };
    UNSAFE_componentWillMount() {
        let _this=this;
        axios.get('http://123.57.67.148:3000/mock/60/postProList')
            .then(function (response) {
                console.log(response.data.data);
                response.data.data.map(item=>item.sum=item.price);
                _this.setState({
                    totalData:response.data.data
                },()=>{})
            })
            .catch(function (error) {
                console.log(error);
            });
    };
}

export default SyContent
